package com.supercell.service;

import com.supercell.misc.concurrent.TCPServer;
import com.supercell.misc.data.TCPConnectionStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by WUJO2 on 7/15/2016.
 */
@Service
public class TCPConnectionService {
    @Autowired
    private DataManipulationService dataManipulationService;
    @Value("#{configProps[TCP_PORT_NUMBER]}")
    private int tcpPortNumber;
    private TCPServer tcpServer;
    private List<TCPConnectionStatus> tcpConnectionStatusList;

    private TCPConnectionService() {
        tcpConnectionStatusList = Collections.synchronizedList(new LinkedList<>());
    }

    public List<TCPConnectionStatus> getTCPConnectionStatus() {
        return tcpConnectionStatusList;
    }

    public boolean isTCPServerRunning() {
        return tcpServer != null && tcpServer.isAlive();
    }

    public void startTCPServer() throws IOException {
        tcpServer = TCPServer.getTCPServerInstance(tcpPortNumber, dataManipulationService, tcpConnectionStatusList);
        tcpServer.start();
    }

    public void stopTCPServer() throws InterruptedException, IOException {
        tcpServer.shutdownTCPServer();
        tcpServer.join();
    }
}
